#!/bin/bash
while getopts "i:o:t:h" arg
do
  case $arg in
    i)
      filename=$OPTARG;;
    o)
      outfile=$OPTARG;;
    t)
      title=$OPTARG;;
    h)
      echo "Example: $0 -i <*.Chr*.plot.txt.gnu.dat>"
      echo "
        -i:   input data
        -o:   output file
        -t:   title for graph
        -h:   print help
      "
      exit 0;;
    ?)
      echo "Unknow argument"
      exit 1;;
  esac
done

if [ ! $filename ];then
  echo "Need -i option!"
  exit 1
fi

if [ ! $outfile ];then
  outfile=$filename'.gnu.ps'
fi

if [ ! $title ];then
  title=unknow
fi
echo "$filename\n$outfile\n$title"
echo "
set term postscript eps dashed color;
set output '$outfile';
set autoscale;
unset key;
set xr [-300:13000];
set multiplot layout 2,1;
set style line 1 lt 1 lc rgb 'blue' lw 3;
set style line 2 lt 1 lc rgb 'black' lw 3;
set style line 3 lt 2 lc rgb 'black' lw 3;
set style line 4 lt 1 lc rgb 'gray' lw 2;
set style line 5 lt 1 lc rgb 'red' lw 6;
set style line 6 lt 1 lc rgb 'cyan' lw 5;
set style line 7 lt 1 lc rgb 'black' lw 5;
set title '$title';
set ylabel 'log2 ratio' offset 2,0,0;
upperdata = system(\"awk '{if(\$9~/^[0-9]+$/)print \$9}' $filename\");
do for [i in upperdata] {
  set arrow from i,-2 to i,2 nohead lt 2 lc rgb 'green' lw 1 front;
}
lowerdata = system(\"awk '{if(\$9~/^[0-9]+$/)print \$10}' $filename\");
do for [i in lowerdata] {
  set arrow from i,-2 to i,2 nohead lt 2 lc rgb 'red' lw 1 front;
}
plot '$filename' using 1:(\$2) with points pt 13 ps 0.17 lc rgb 'gray',\
       '' using 1:(\$3) with lines ls 1,\
       0 with lines ls 2,\
       -1 with lines ls 3,\
       0.5849625 with lines ls 3,\
       '' using 1:(\$6) with lines ls 5,\
       '' using 1:(\$7) with lines ls 6,\
       '' using 1:(\$8) with lines ls 7;
set title '';
set ylabel 'z value';
set yr [-10:10];
set ytics(-10,-5,0,5,10);
set xlabel 'Blocks(20000*1)';
do for [i in upperdata] {
  set arrow from i,-10 to i,10 nohead lt 2 lc rgb 'green' lw 1 front;
}
do for [i in lowerdata] {
  set arrow from i,-10 to i,10 nohead lt 2 lc rgb 'red' lw 1 front;
}
plot '$filename' using 1:(\$4) with lines ls 4,\
       '' using 1:(\$5) with lines ls 1,\
       0 with lines ls 2,\
       3 with lines ls 3,\
       -3 with lines ls 3,\
       '' using 1:(\$6) with lines ls 5,\
       '' using 1:(\$7) with lines ls 6,\
       '' using 1:(\$8) with lines ls 7;
" | gnuplot
